// src/stores/modal.ts
import { defineStore } from 'pinia'
import { ref, shallowRef, type Component } from 'vue'

// 定义单个弹框的配置接口
export interface ModalConfig {
  id: string
  component: Component // 要渲染的组件
  props?: Record<string, any> // 传递给组件的 props
  options?: ModalOptions // 弹框本身的配置
}

// 定义弹框的可选配置
export interface ModalOptions {
  position?: 'top' | 'center' | 'bottom' | { target: HTMLElement; offset: [number, number] }
  animationType?: 'fade' | 'slide-up' | 'slide-down' | 'none'
  showOverlay?: boolean
  overlayColor?: string
  closeOnClickOverlay?: boolean
  duration?: number; //自动关闭的延迟时间 (ms)
  showClose?:boolean, // 是否显示关闭图标
}

let idCounter = 0

export const useModalStore = defineStore('modal', () => {
  const modals = ref<ModalConfig[]>([])

  // 显示一个新弹框
  function show(component: Component, props?: Record<string, any>, options?: ModalOptions) {
    const id = `modal-${idCounter++}`
    modals.value.push({
      id,
      component: shallowRef(component), // 使用 shallowRef 避免深度代理组件对象
      props,
      options,
    })
    return id
  }

  // 根据 ID 隐藏一个弹框
  function hide(id: string) {
    
    const index = modals.value.findIndex((m) => m.id === id)
    if (index > -1) {
      modals.value.splice(index, 1)
    }
  }

  // 隐藏所有弹框
  function hideAll() {
    modals.value = []
  }

  return { modals, show, hide, hideAll }
})
